package com.xq.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.google.common.base.Strings;
import com.google.gson.GsonBuilder;
import com.jfinal.core.Controller;
import com.jfinal.log.Logger;
import com.jfinal.plugin.activerecord.Page;
import com.xq.model.Comment;


public class CommentController extends Controller {

	private static Logger logger = Logger.getLogger(CommentController.class);
	
	// response is like {"content":"{\"list\":[{\"childComments\":[],\"user.room\":802,\"targetId\":1,\"user.nick\":\"he dashi\",\"content\":\"bad\",\"id\":1,\"user.id\":1,\"userId\":1,\"user.xiaoqu.name\":\"保利西子湾\",\"user.xiaoQuId\":1,\"target\":1,\"user.unit\":143,\"createDate\":\"Jun 17, 2014 3:40:32 PM\"}],\"totalRow\":1,\"totalPage\":1}","message":"","status":1}
	public void shopComment()
	{
		int shopId = getParaToInt(0);
		int pageNumber = getParaToInt("pageNumber", 1);
		int pageSize = getParaToInt("pageSize", 10);
		Page<Comment> pageComments = Comment.dao.findTopCommentsByTargetId(Comment.TARGET_SHOP, shopId, pageNumber, pageSize);
		
		Map<String, Object> result = new HashMap<String, Object>();
		
		List<Map<String, Object>> commentAttrsList = new ArrayList<Map<String, Object>>();
		for(Comment comment: pageComments.getList())
		{
			Map<String, Object> commentAttrs = comment.cloneAttrs();
			List<Comment> childCommentList = Comment.dao.findChildCommentList((Integer)commentAttrs.get("id"));
			List<Map> childCommentAttrsList = new ArrayList<Map>();
			for(Comment childComment: childCommentList)
			{
				childCommentAttrsList.add(childComment.cloneAttrs());
			}
			commentAttrs.put("childComments", childCommentAttrsList);
			commentAttrsList.add(commentAttrs);
		}
		result.put("totalPage", pageComments.getTotalPage());
		result.put("totalRow", pageComments.getTotalRow());
		result.put("list", commentAttrsList);
		String content = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create().toJson(result);
		XQResponse response = new XQResponse(XQResponse.STATUS_SUCCESS, "", content);
		renderJson(response);
	
	}
	
	public void create()
	{
		String content = getPara("comment.content");
		String target = getPara("comment.target");
		String targetId = getPara("comment.targetId");
		String parentId = getPara("comment.parentId");
		//String userId = getPara("comment.userId");
		//User from AuthenticationInterceptor
		Map<String, Object> user = (Map<String, Object>)getAttr("user");
		Comment comment = new Comment();
		comment.set("content", content);
		comment.set("target", Integer.valueOf(target));
		comment.set("targetId", targetId);
		comment.set("parentId", Strings.isNullOrEmpty(parentId)? null: Integer.valueOf(parentId));
		comment.set("userId", user.get("id"));
		comment.save();
		renderJson(new XQResponse(XQResponse.STATUS_SUCCESS, "", comment.getInt("id") + ""));
	}

	
}
